home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / overload.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  18.5 KB  |  597 lines

  1. package overload;
  2.  
  3. sub nil {}
  4.  
  5. sub OVERLOAD {
  6.   $package = shift;
  7.   my %arg = @_;
  8.   my ($sub, $fb);
  9.   $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
  10.   *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
  11.   for (keys %arg) {
  12.     if ($_ eq 'fallback') {
  13.       $fb = $arg{$_};
  14.     } else {
  15.       $sub = $arg{$_};
  16.       if (not ref $sub and $sub !~ /::/) {
  17.     $ {$package . "::(" . $_} = $sub;
  18.     $sub = \&nil;
  19.       }
  20.       *{$package . "::(" . $_} = \&{ $sub };
  21.     }
  22.   }
  23.   ${$package . "::()"} = $fb; # Make it findable too (fallback only).
  24. }
  25.  
  26. sub import {
  27.   $package = (caller())[0];
  28.   shift;
  29.   $package->overload::OVERLOAD(@_);
  30. }
  31.  
  32. sub unimport {
  33.   $package = (caller())[0];
  34.   ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
  35.   shift;
  36.   for (@_) {
  37.     if ($_ eq 'fallback') {
  38.       undef $ {$package . "::()"};
  39.     } else {
  40.       delete $ {$package . "::"}{"(" . $_};
  41.     }
  42.   }
  43. }
  44.  
  45. sub Overloaded {
  46.   my $package = shift;
  47.   $package = ref $package if ref $package;
  48.   $package->can('()');
  49. }
  50.  
  51. sub ov_method {
  52.   my $globref = shift;
  53.   return undef unless $globref;
  54.   my $sub = \&{*$globref};
  55.   return $sub if $sub ne \&nil;
  56.   return shift->can($ {*$globref});
  57. }
  58.  
  59. sub OverloadedStringify {
  60.   my $package = shift;
  61.   $package = ref $package if ref $package;
  62.   ov_method mycan($package, '(""'), $package;
  63. }
  64.  
  65. sub Method {
  66.   my $package = shift;
  67.   $package = ref $package if ref $package;
  68.   ov_method mycan($package, '(' . shift), $package;
  69. }
  70.  
  71. sub AddrRef {
  72.   my $package = ref $_[0];
  73.   return "$_[0]" unless $package;
  74.   bless $_[0], overload::Fake;    # Non-overloaded package
  75.   my $str = "$_[0]";
  76.   bless $_[0], $package;    # Back
  77.   $package . substr $str, index $str, '=';
  78. }
  79.  
  80. sub StrVal {
  81.   (OverloadedStringify($_[0])) ?
  82.     (AddrRef(shift)) :
  83.     "$_[0]";
  84. }
  85.  
  86. sub mycan {                # Real can would leave stubs.
  87.   my ($package, $meth) = @_;
  88.   return \*{$package . "::$meth"} if defined &{$package . "::$meth"};
  89.   my $p;
  90.   foreach $p (@{$package . "::ISA"}) {
  91.     my $out = mycan($p, $meth);
  92.     return $out if $out;
  93.   }
  94.   return undef;
  95. }
  96.  
  97. 1;
  98.  
  99. __END__
  100.  
  101. =head1 NAME 
  102.  
  103. overload - Package for overloading perl operations
  104.  
  105. =head1 SYNOPSIS
  106.  
  107.     package SomeThing;
  108.  
  109.     use overload 
  110.     '+' => \&myadd,
  111.     '-' => \&mysub;
  112.     ...
  113.  
  114.     package main;
  115.     $a = new SomeThing 57;
  116.     $b=5+$a;
  117.     ...
  118.     if (overload::Overloaded $b) {...}
  119.     ...
  120.     $strval = overload::StrVal $b;
  121.  
  122. =head1 CAVEAT SCRIPTOR
  123.  
  124. Overloading of operators is a subject not to be taken lightly.
  125. Neither its precise implementation, syntax, nor semantics are
  126. 100% endorsed by Larry Wall.  So any of these may be changed 
  127. at some point in the future.
  128.  
  129. =head1 DESCRIPTION
  130.  
  131. =head2 Declaration of overloaded functions
  132.  
  133. The compilation directive
  134.  
  135.     package Number;
  136.     use overload
  137.     "+" => \&add, 
  138.     "*=" => "muas";
  139.  
  140. declares function Number::add() for addition, and method muas() in
  141. the "class" C<Number> (or one of its base classes)
  142. for the assignment form C<*=> of multiplication.  
  143.  
  144. Arguments of this directive come in (key, value) pairs.  Legal values
  145. are values legal inside a C<&{ ... }> call, so the name of a
  146. subroutine, a reference to a subroutine, or an anonymous subroutine
  147. will all work.  Note that values specified as strings are
  148. interpreted as methods, not subroutines.  Legal keys are listed below.
  149.  
  150. The subroutine C<add> will be called to execute C<$a+$b> if $a
  151. is a reference to an object blessed into the package C<Number>, or if $a is
  152. not an object from a package with defined mathemagic addition, but $b is a
  153. reference to a C<Number>.  It can also be called in other situations, like
  154. C<$a+=7>, or C<$a++>.  See L<MAGIC AUTOGENERATION>.  (Mathemagical
  155. methods refer to methods triggered by an overloaded mathematical
  156. operator.)
  157.  
  158. Since overloading respects inheritance via the @ISA hierarchy, the
  159. above declaration would also trigger overloading of C<+> and C<*=> in
  160. all the packages which inherit from C<Number>.
  161.  
  162. =head2 Calling Conventions for Binary Operations
  163.  
  164. The functions specified in the C<use overload ...> directive are called
  165. with three (in one particular case with four, see L<Last Resort>)
  166. arguments.  If the corresponding operation is binary, then the first
  167. two arguments are the two arguments of the operation.  However, due to
  168. general object calling conventions, the first argument should always be
  169. an object in the package, so in the situation of C<7+$a>, the
  170. order of the arguments is interchanged.  It probably does not matter
  171. when implementing the addition method, but whether the arguments
  172. are reversed is vital to the subtraction method.  The method can
  173. query this information by examining the third argument, which can take
  174. three different values:
  175.  
  176. =over 7
  177.  
  178. =item FALSE
  179.  
  180. the order of arguments is as in the current operation.
  181.  
  182. =item TRUE
  183.  
  184. the arguments are reversed.
  185.  
  186. =item C<undef>
  187.  
  188. the current operation is an assignment variant (as in
  189. C<$a+=7>), but the usual function is called instead.  This additional
  190. information can be used to generate some optimizations.
  191.  
  192. =back
  193.  
  194. =head2 Calling Conventions for Unary Operations
  195.  
  196. Unary operation are considered binary operations with the second
  197. argument being C<undef>.  Thus the functions that overloads C<{"++"}>
  198. is called with arguments C<($a,undef,'')> when $a++ is executed.
  199.  
  200. =head2 Overloadable Operations
  201.  
  202. The following symbols can be specified in C<use overload>:
  203.  
  204. =over 5
  205.  
  206. =item * I<Arithmetic operations>
  207.  
  208.     "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
  209.     "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
  210.  
  211. For these operations a substituted non-assignment variant can be called if
  212. the assignment variant is not available.  Methods for operations "C<+>",
  213. "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
  214. increment and decrement methods.  The operation "C<->" can be used to
  215. autogenerate missing methods for unary minus or C<abs>.
  216.  
  217. =item * I<Comparison operations>
  218.  
  219.     "<",  "<=", ">",  ">=", "==", "!=", "<=>",
  220.     "lt", "le", "gt", "ge", "eq", "ne", "cmp",
  221.  
  222. If the corresponding "spaceship" variant is available, it can be
  223. used to substitute for the missing operation.  During C<sort>ing
  224. arrays, C<cmp> is used to compare values subject to C<use overload>.
  225.  
  226. =item * I<Bit operations>
  227.  
  228.     "&", "^", "|", "neg", "!", "~",
  229.  
  230. "C<neg>" stands for unary minus.  If the method for C<neg> is not
  231. specified, it can be autogenerated using the method for
  232. subtraction. If the method for "C<!>" is not specified, it can be
  233. autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
  234.  
  235. =item * I<Increment and decrement>
  236.  
  237.     "++", "--",
  238.  
  239. If undefined, addition and subtraction methods can be
  240. used instead.  These operations are called both in prefix and
  241. postfix form.
  242.  
  243. =item * I<Transcendental functions>
  244.  
  245.     "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
  246.  
  247. If C<abs> is unavailable, it can be autogenerated using methods
  248. for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
  249.  
  250. =item * I<Boolean, string and numeric conversion>
  251.  
  252.     "bool", "\"\"", "0+",
  253.  
  254. If one or two of these operations are unavailable, the remaining ones can
  255. be used instead.  C<bool> is used in the flow control operators
  256. (like C<while>) and for the ternary "C<?:>" operation.  These functions can
  257. return any arbitrary Perl value.  If the corresponding operation for this value
  258. is overloaded too, that operation will be called again with this value.
  259.  
  260. =item * I<Special>
  261.  
  262.     "nomethod", "fallback", "=",
  263.  
  264. see L<SPECIAL SYMBOLS FOR C<use overload>>.
  265.  
  266. =back
  267.  
  268. See L<"Fallback"> for an explanation of when a missing method can be autogenerated.
  269.  
  270. =head2 Inheritance and overloading
  271.  
  272. Inheritance interacts with overloading in two ways.
  273.  
  274. =over
  275.  
  276. =item Strings as values of C<use overload> directive
  277.  
  278. If C<value> in
  279.  
  280.   use overload key => value;
  281.  
  282. is a string, it is interpreted as a method name.
  283.  
  284. =item Overloading of an operation is inherited by derived classes
  285.  
  286. Any class derived from an overloaded class is also overloaded.  The
  287. set of overloaded methods is the union of overloaded methods of all
  288. the ancestors. If some method is overloaded in several ancestor, then
  289. which description will be used is decided by the usual inheritance
  290. rules:
  291.  
  292. If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
  293. C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
  294. then the subroutine C<D::plus_sub> will be called to implement
  295. operation C<+> for an object in package C<A>.
  296.  
  297. =back
  298.  
  299. Note that since the value of the C<fallback> key is not a subroutine,
  300. its inheritance is not governed by the above rules.  In the current
  301. implementation, the value of C<fallback> in the first overloaded
  302. ancestor is used, but this is accidental and subject to change.
  303.  
  304. =head1 SPECIAL SYMBOLS FOR C<use overload>
  305.  
  306. Three keys are recognized by Perl that are not covered by the above
  307. description.
  308.  
  309. =head2 Last Resort
  310.  
  311. C<"nomethod"> should be followed by a reference to a function of four
  312. parameters.  If defined, it is called when the overloading mechanism
  313. cannot find a method for some operation.  The first three arguments of
  314. this function coincide with the arguments for the corresponding method if
  315. it were found, the fourth argument is the symbol
  316. corresponding to the missing method.  If several methods are tried,
  317. the last one is used.  Say, C<1-$a> can be equivalent to
  318.  
  319.     &nomethodMethod($a,1,1,"-")
  320.  
  321. if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
  322. C<use overload> directive.
  323.  
  324. If some operation cannot be resolved, and there is no function
  325. assigned to C<"nomethod">, then an exception will be raised via die()--
  326. unless C<"fallback"> was specified as a key in C<use overload> directive.
  327.  
  328. =head2 Fallback 
  329.  
  330. The key C<"fallback"> governs what to do if a method for a particular
  331. operation is not found.  Three different cases are possible depending on
  332. the value of C<"fallback">:
  333.  
  334. =over 16
  335.  
  336. =item * C<undef>
  337.  
  338. Perl tries to use a
  339. substituted method (see L<MAGIC AUTOGENERATION>).  If this fails, it
  340. then tries to calls C<"nomethod"> value; if missing, an exception
  341. will be raised.
  342.  
  343. =item * TRUE
  344.  
  345. The same as for the C<undef> value, but no exception is raised.  Instead,
  346. it silently reverts to what it would have done were there no C<use overload>
  347. present.
  348.  
  349. =item * defined, but FALSE
  350.  
  351. No autogeneration is tried.  Perl tries to call
  352. C<"nomethod"> value, and if this is missing, raises an exception. 
  353.  
  354. =back
  355.  
  356. B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
  357. yet, see L<"Inheritance and overloading">.
  358.  
  359. =head2 Copy Constructor
  360.  
  361. The value for C<"="> is a reference to a function with three
  362. arguments, i.e., it looks like the other values in C<use
  363. overload>. However, it does not overload the Perl assignment
  364. operator. This would go against Camel hair.
  365.  
  366. This operation is called in the situations when a mutator is applied
  367. to a reference that shares its object with some other reference, such
  368. as
  369.  
  370.     $a=$b; 
  371.     $a++;
  372.  
  373. To make this change $a and not change $b, a copy of C<$$a> is made,
  374. and $a is assigned a reference to this new object.  This operation is
  375. done during execution of the C<$a++>, and not during the assignment,
  376. (so before the increment C<$$a> coincides with C<$$b>).  This is only
  377. done if C<++> is expressed via a method for C<'++'> or C<'+='>.  Note
  378. that if this operation is expressed via C<'+'> a nonmutator, i.e., as
  379. in
  380.  
  381.     $a=$b; 
  382.     $a=$a+1;
  383.  
  384. then C<$a> does not reference a new copy of C<$$a>, since $$a does not
  385. appear as lvalue when the above code is executed.
  386.  
  387. If the copy constructor is required during the execution of some mutator,
  388. but a method for C<'='> was not specified, it can be autogenerated as a
  389. string copy if the object is a plain scalar.
  390.  
  391. =over 5
  392.  
  393. =item B<Example>
  394.  
  395. The actually executed code for 
  396.  
  397.     $a=$b; 
  398.         Something else which does not modify $a or $b....
  399.     ++$a;
  400.  
  401. may be
  402.  
  403.     $a=$b; 
  404.         Something else which does not modify $a or $b....
  405.     $a = $a->clone(undef,"");
  406.         $a->incr(undef,"");
  407.  
  408. if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
  409. C<'='> was overloaded with C<\&clone>.
  410.  
  411. =back
  412.  
  413. =head1 MAGIC AUTOGENERATION
  414.  
  415. If a method for an operation is not found, and the value for  C<"fallback"> is
  416. TRUE or undefined, Perl tries to autogenerate a substitute method for
  417. the missing operation based on the defined operations.  Autogenerated method
  418. substitutions are possible for the following operations:
  419.  
  420. =over 16
  421.  
  422. =item I<Assignment forms of arithmetic operations>
  423.  
  424. C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
  425. is not defined.
  426.  
  427. =item I<Conversion operations> 
  428.  
  429. String, numeric, and boolean conversion are calculated in terms of one
  430. another if not all of them are defined.
  431.  
  432. =item I<Increment and decrement>
  433.  
  434. The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
  435. and C<$a--> in terms of C<$a-=1> and C<$a-1>.
  436.  
  437. =item C<abs($a)>
  438.  
  439. can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
  440.  
  441. =item I<Unary minus>
  442.  
  443. can be expressed in terms of subtraction.
  444.  
  445. =item I<Negation>
  446.  
  447. C<!> and C<not> can be expressed in terms of boolean conversion, or
  448. string or numerical conversion.
  449.  
  450. =item I<Concatenation>
  451.  
  452. can be expressed in terms of string conversion.
  453.  
  454. =item I<Comparison operations> 
  455.  
  456. can be expressed in terms of its "spaceship" counterpart: either
  457. C<E<lt>=E<gt>> or C<cmp>:
  458.  
  459.     <, >, <=, >=, ==, !=     in terms of <=>
  460.     lt, gt, le, ge, eq, ne     in terms of cmp
  461.  
  462. =item I<Copy operator>
  463.  
  464. can be expressed in terms of an assignment to the dereferenced value, if this
  465. value is a scalar and not a reference.
  466.  
  467. =back
  468.  
  469. =head1 WARNING
  470.  
  471. The restriction for the comparison operation is that even if, for example,
  472. `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
  473. function will produce only a standard logical value based on the
  474. numerical value of the result of `C<cmp>'.  In particular, a working
  475. numeric conversion is needed in this case (possibly expressed in terms of
  476. other conversions).
  477.  
  478. Similarly, C<.=>  and C<x=> operators lose their mathemagical properties
  479. if the string conversion substitution is applied.
  480.  
  481. When you chop() a mathemagical object it is promoted to a string and its
  482. mathemagical properties are lost.  The same can happen with other
  483. operations as well.
  484.  
  485. =head1 Run-time Overloading
  486.  
  487. Since all C<use> directives are executed at compile-time, the only way to
  488. change overloading during run-time is to
  489.  
  490.     eval 'use overload "+" => \&addmethod';
  491.  
  492. You can also use
  493.  
  494.     eval 'no overload "+", "--", "<="';
  495.  
  496. though the use of these constructs during run-time is questionable.
  497.  
  498. =head1 Public functions
  499.  
  500. Package C<overload.pm> provides the following public functions:
  501.  
  502. =over 5
  503.  
  504. =item overload::StrVal(arg)
  505.  
  506. Gives string value of C<arg> as in absence of stringify overloading.
  507.  
  508. =item overload::Overloaded(arg)
  509.  
  510. Returns true if C<arg> is subject to overloading of some operations.
  511.  
  512. =item overload::Method(obj,op)
  513.  
  514. Returns C<undef> or a reference to the method that implements C<op>.
  515.  
  516. =back
  517.  
  518. =head1 IMPLEMENTATION
  519.  
  520. What follows is subject to change RSN.
  521.  
  522. The table of methods for all operations is cached in magic for the
  523. symbol table hash for the package.  The cache is invalidated during
  524. processing of C<use overload>, C<no overload>, new function
  525. definitions, and changes in @ISA. However, this invalidation remains
  526. unprocessed until the next C<bless>ing into the package. Hence if you
  527. want to change overloading structure dynamically, you'll need an
  528. additional (fake) C<bless>ing to update the table.
  529.  
  530. (Every SVish thing has a magic queue, and magic is an entry in that
  531. queue.  This is how a single variable may participate in multiple
  532. forms of magic simultaneously.  For instance, environment variables
  533. regularly have two forms at once: their %ENV magic and their taint
  534. magic. However, the magic which implements overloading is applied to
  535. the stashes, which are rarely used directly, thus should not slow down
  536. Perl.)
  537.  
  538. If an object belongs to a package using overload, it carries a special
  539. flag.  Thus the only speed penalty during arithmetic operations without
  540. overloading is the checking of this flag.
  541.  
  542. In fact, if C<use overload> is not present, there is almost no overhead
  543. for overloadable operations, so most programs should not suffer
  544. measurable performance penalties.  A considerable effort was made to
  545. minimize the overhead when overload is used in some package, but the
  546. arguments in question do not belong to packages using overload.  When
  547. in doubt, test your speed with C<use overload> and without it.  So far
  548. there have been no reports of substantial speed degradation if Perl is
  549. compiled with optimization turned on.
  550.  
  551. There is no size penalty for data if overload is not used. The only
  552. size penalty if overload is used in some package is that I<all> the
  553. packages acquire a magic during the next C<bless>ing into the
  554. package. This magic is three-words-long for packages without
  555. overloading, and carries the cache tabel if the package is overloaded.
  556.  
  557. Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is 
  558. carried out before any operation that can imply an assignment to the
  559. object $a (or $b) refers to, like C<$a++>.  You can override this
  560. behavior by defining your own copy constructor (see L<"Copy Constructor">).
  561.  
  562. It is expected that arguments to methods that are not explicitly supposed
  563. to be changed are constant (but this is not enforced).
  564.  
  565. =head1 AUTHOR
  566.  
  567. Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
  568.  
  569. =head1 DIAGNOSTICS
  570.  
  571. When Perl is run with the B<-Do> switch or its equivalent, overloading
  572. induces diagnostic messages.
  573.  
  574. Using the C<m> command of Perl debugger (see L<perldebug>) one can
  575. deduce which operations are overloaded (and which ancestor triggers
  576. this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
  577. is shown by debugger. The method C<()> corresponds to the C<fallback>
  578. key (in fact a presence of this method shows that this package has
  579. overloading enabled, and it is what is used by the C<Overloaded>
  580. function).
  581.  
  582. =head1 BUGS
  583.  
  584. Because it is used for overloading, the per-package hash %OVERLOAD now
  585. has a special meaning in Perl. The symbol table is filled with names
  586. looking like line-noise.
  587.  
  588. For the purpose of inheritance every overloaded package behaves as if
  589. C<fallback> is present (possibly undefined). This may create
  590. interesting effects if some package is not overloaded, but inherits
  591. from two overloaded packages.
  592.  
  593. This document is confusing.
  594.  
  595. =cut
  596.  
  597.